package com.fitzone.web.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fitzone.common.enums.BusinessType;
import com.fitzone.common.exception.LoginFailedException;
import com.fitzone.common.result.Result;
import com.fitzone.model.dto.StorePageDTO;
import com.fitzone.model.dto.StoreDTO;
import com.fitzone.model.entity.Banner;
import com.fitzone.model.entity.CoachPhoto;
import com.fitzone.model.entity.Store;
import com.fitzone.model.entity.SysUser;
import com.fitzone.model.vo.StoreVO;
import com.fitzone.web.annotation.Log;
import com.fitzone.web.service.BannerService;
import com.fitzone.web.service.StoreService;
import com.fitzone.web.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.lang.annotation.ElementType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Api(tags = "门店管理")
@RestController
@RequestMapping("/admin/store")
@RequiredArgsConstructor
public class StoreController {

    private final StoreService storeService;
    private final SysUserService sysUserService;
    private final BannerService bannerService;

    @Log(title = "门店管理", businessType = BusinessType.INSERT)
    @PostMapping
    @PreAuthorize("hasAuthority('bnt.store.add')")
    @ApiOperation("添加操作")
    public Result save(@RequestBody StoreDTO storeDTO) {
        storeService.saveStore(storeDTO);
        return Result.ok();
    }

    @Log(title = "门店管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @PreAuthorize("hasAuthority('bnt.store.update')")
    @ApiOperation("修改操作")
    public Result update(@RequestBody StoreDTO storeDTO) {
        storeService.updateStore(storeDTO);
        return Result.ok();
    }

    @Log(title = "门店管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('bnt.store.remove')")
    @ApiOperation("删除操作")
    public Result delete(@PathVariable Long id) {
        storeService.removeById(id);
        return Result.ok();
    }

    @PreAuthorize("hasAuthority('bnt.sysUser.list')")
    @ApiOperation(value = "根据id查询")
    @GetMapping("/{id}")
    public Result getId(@PathVariable Long id) {
        Store store = storeService.getById(id);
        StoreVO storeVO = new StoreVO();
        BeanUtils.copyProperties(store, storeVO);
        LambdaQueryWrapper<Banner> queryWrapper = new LambdaQueryWrapper<Banner>().eq(Banner::getStoreId, id);
        List<Banner> bannerList = bannerService.list(queryWrapper);
        storeVO.setBanner(bannerList);
        return Result.ok(storeVO);
    }

    @ApiOperation(value = "获取分页列表")
    @GetMapping("/{page}/{limit}")
    @PreAuthorize("hasAuthority('bnt.sysUser.list')")
    public Result<Page> page(StorePageDTO storePageDTO) {
        Long principal = (Long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal == null){
            throw new LoginFailedException("账号错误");
        }
        SysUser user = sysUserService.getById(principal);

        Page<Store> pageInfo = new Page<>(storePageDTO.getPage(), storePageDTO.getLimit());
        Page<StoreVO> storePageInfo = new Page<>();
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(storePageDTO.getStoreName() != null, Store::getStoreName, storePageDTO.getStoreName())
                .orderByDesc(Store::getCreateTime)
                .eq(user.getStoreId() != null,Store::getId,user.getStoreId());
        storeService.page(pageInfo,queryWrapper);
        BeanUtils.copyProperties(pageInfo, storePageDTO, "records");
        List<Store> store = pageInfo.getRecords();
        List<StoreVO> list = store.stream().map(item -> {
            LambdaQueryWrapper<Banner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Banner::getStoreId, item.getId());
            List<Banner> bannerList = bannerService.list(lambdaQueryWrapper);

            StoreVO storeVO = new StoreVO();
            BeanUtils.copyProperties(item, storeVO);
            storeVO.setBanner(bannerList);

            return storeVO;
        }).collect(Collectors.toList());
        storePageInfo.setRecords(list);
        return Result.ok(storePageInfo);
    }

    @GetMapping("/list")
    @ApiOperation(value = "查询所有")
    @PreAuthorize("hasAuthority('bnt.sysUser.list')")
    public Result<List<Map>> getAll(){
        Long principal = (Long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal == null){
            throw new LoginFailedException("账号错误");
        }
        SysUser user = sysUserService.getById(principal);

        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(user.getStoreId() != null,Store::getId,user.getStoreId());

        List<Store> list = storeService.list(queryWrapper);

        List<Map> maps = new ArrayList<>();
        for (Store store : list) {
            Map map = new HashMap();
            map.put("id",store.getId());
            map.put("storeName",store.getStoreName());
            maps.add(map);
        }
        return Result.ok(maps);
    }
}
